package com.ap.core.backoffice.dao;

import com.ap.core.backoffice.domain.Identifiable;
import org.hibernate.Session;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * User: Ranjit.Singh
 * Base JPA implementation for all DAOs.
 * 
 * @param <T>
 *            generic type for the persistent entity
 * @param <U>
 *            generic type for the primary key of the entity
 */
public abstract class AbstractReadOnlyAPCoreBOBaseJpaDao<T extends Identifiable<U>, U> implements ReadOnlyGenericDao<T, U> {

    /** Entity Manager */
    private EntityManager entityManager;

    /**
     * Sets the entity manager.
     * 
     * @param pEntityManager
     *            the new entity manager
     */
    @PersistenceContext(unitName="ap-core-backoffice")
    protected void setEntityManager(final EntityManager pEntityManager) {
        this.entityManager = pEntityManager;
    }



    @Override
    public void flush() {
        entityManager.flush();
    }


    @Override
    public void clear() {
        entityManager.clear();
    }

    /**
     * Find entity instance by id.
     * 
     * @param entityClass
     *            the entity class
     * @param primaryKey
     *            primary key for the entity
     * @return the found instance of the entity class
     */
    protected T findById(final Class<T> entityClass, final U primaryKey) {
        return entityManager.find(entityClass, primaryKey);
    }

    public Session getSession() {
        return (Session) entityManager.getDelegate();
    }

}